What is es-to-primitive?
The es-to-primitive npm package provides functionality to convert a JavaScript value to its primitive equivalent, following the ECMAScript specification for ToPrimitive abstract operation. It handles the conversion according to the preferred type hint, either Number or String.
What are es-to-primitive's main functionalities?
Converting to primitive with no hint
This code converts a Date object to its primitive value without specifying a type hint. The default hint will be applied based on the object type.
var toPrimitive = require('es-to-primitive');
var obj = new Date();
var primitiveValue = toPrimitive(obj);
Converting to primitive with a hint of Number
This code converts a Date object to its primitive value with a type hint of Number, which means it will prefer the numeric value of the Date (timestamp).
var toPrimitive = require('es-to-primitive');
var obj = new Date();
var primitiveValue = toPrimitive(obj, Number);
Converting to primitive with a hint of String
This code converts an object with both toString and valueOf methods to its primitive value with a type hint of String, which means it will prefer the string representation 'foo'.
var toPrimitive = require('es-to-primitive');
var obj = { toString: function() { return 'foo'; }, valueOf: function() { return 42; } };
var primitiveValue = toPrimitive(obj, String);
Other packages similar to es-to-primitive
to-primitive
The to-primitive package is another alternative that offers similar functionality to es-to-primitive. It aims to provide a reliable way to get the primitive value of objects but may have different internal implementations or API design.